<template>
  <div class="content-block">
    <div class="content-main">
      <div class="content-title">
        <div class="title-text-dot">企业列表</div>
        <div class="title-handle">
          <div class="handel-item">
            <el-button type="primary" size="mini" @click="handleAdd"
              >新 增</el-button
            >
          </div>
          <div class="handel-item">
            <el-button type="primary" size="mini" @click="handleSearch"
              >查 询</el-button
            >
          </div>
          <div class="handel-item">
            <el-button type="primary" size="mini" @click="exportExcle"
              >导 出</el-button
            >
          </div>
          <div class="handel-item">
            <el-input
              v-model="wuqTitle"
              size="mini"
              type="text"
              placeholder="企业名称"
            ></el-input>
          </div>
        </div>
      </div>
      <el-table
        :data="companyList"
        border
        size="mini"
        height="calc(100vh - 230px)"
        v-loading="tableLoading"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          align="center"
          width="50"
        ></el-table-column>
        <el-table-column label="企业名称" prop="wuqTitle"></el-table-column>
        <el-table-column label="法人" prop="wuqName"></el-table-column>
        <el-table-column label="手机号" prop="wuqPhone"></el-table-column>
        <el-table-column label="地址" prop="wuqArea"></el-table-column>
        <el-table-column label="余额" prop="balance">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.balance) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="wuqStatus">
          <template slot-scope="scope">
            <span>{{ scope.row.wuqStatus | wuqStatusName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              title="编辑"
              class="text-blue"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              title="审核"
              class="text-orange"
              @click="audit(scope.row)"
            >审核</el-button>
            <el-button
              size="mini"
              type="text"
              title="注销"
              class="text-red"
              @click="handleDelete(scope.row)"
              >注销</el-button
            >
            <el-button
              size="mini"
              type="text"
              title="注销"
              class="text-green"
              @click="handleRecharge(scope.row)"
              >充值</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        :total="total"
      ></el-pagination>
      <!--操作弹窗-->
      <el-dialog
        :close-on-click-modal="false"
        :title="handleTitle"
        :visible.sync="handleVisible"
        width="50%"
        center
      >
        <el-form
          ref="companyForm"
          :model="companyForm"
          :rules="companyFormRule"
          status-icon
          label-width="90px"
          size="small"
        >
          <el-form-item label="企业名称" prop="wuqTitle">
            <el-row>
              <el-col :span="24">
                <el-input
                  v-model.trim="companyForm.wuqTitle"
                  type="text"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="法人" prop="wuqName">
            <el-row>
              <el-col :span="24">
                <el-input
                  v-model.trim="companyForm.wuqName"
                  type="text"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="法人身份证" prop="wuqCard">
            <el-row>
              <el-col :span="24">
                <el-input
                  v-model.trim="companyForm.wuqCard"
                  type="text"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="联系方式" prop="wuqPhone">
            <el-row>
              <el-col :span="24">
                <el-input
                  v-model.trim="companyForm.wuqPhone"
                  type="text"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="上传图片" prop="wuqLicense">
            <el-progress
              :percentage="percentageNum"
              v-if="showProgress"
            ></el-progress>
            <div class="upload-row">
              <el-upload
                action
                :show-file-list="false"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="companyForm.wuqLicense"
                  :src="$global.baseUrl + companyForm.wuqLicense"
                  style="width: 200px; height: 200px"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="打卡范围" prop="allowedRange">
            <el-row>
              <el-col :span="24">
                <el-input
                  v-model.trim="companyForm.allowedRange"
                  type="text"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="地址" prop="wuqArea">
            <el-input v-model="companyForm.wuqArea"></el-input>
            <el-button size="mini" type="primary" @click="getAddressKeyword"
              >搜索</el-button
            >
            <!-- 渲染地图的div容器 -->
            <div id="container" style="width: 100%; height: 300px"></div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleVisible = false" size="mini"
            >取 消</el-button
          >
          <el-button type="primary" @click="handleSave" size="mini"
            >保 存</el-button
          >
        </div>
      </el-dialog>

      <!-- 注销弹窗 -->
      <el-dialog
        :close-on-click-modal="false"
        title="注销企业"
        :visible.sync="delVisible"
        width="260px"
        center
      >
        <div class="del-dialog-cnt">注销不可恢复，是否确定注销？</div>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="delVisible = false">取 消</el-button>
          <el-button size="mini" type="danger" @click="deleteRow"
            >注 销</el-button
          >
        </span>
      </el-dialog>

      <!--充值操作弹窗-->
      <el-dialog
        :close-on-click-modal="false"
        title="充值"
        :visible.sync="rechargeVisible"
        width="260px"
        center
      >
        <el-form
          ref="rechargeForm"
          :model="rechargeForm"
          status-icon
          label-width="90px"
          size="small"
        >
          <el-form-item label="充值金额" prop="balance">
            <el-row>
              <el-col :span="24">
                <currency-input
                  v-model.trim="rechargeForm.balance"
                ></currency-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="rechargeVisible = false"
            >取 消</el-button
          >
          <el-button size="mini" type="primary" @click="optRecharge"
            >充 值</el-button
          >
        </span>
      </el-dialog>
      <!--审核弹窗-->
      <el-dialog
        title="审核意见"
        :visible.sync="dialogVisibleAuth"
        width="30%"
      >
        <div>
          <el-form>
            <el-form-item>
              <el-input placeholder="请输入审核意见" v-model="formAuth"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisibleAuth = false">取 消</el-button>
          <el-button size="small" type="danger" @click="rejected"
            >驳 回</el-button
          >
          <el-button size="small" type="primary" @click="saveAuth"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import Api from "../../constants/Api";
import xlsx from "@/utils/xlsx";
import { check_api } from "@/api/company.js";
// 引入qqmap
import maps from "qqmap";
// import the styles
export default {
  data() {
    const vm = this;
    let valCard = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("法人身份证不为空"));
      } else if (!vm.regExIdCard(value)) {
        return callback(new Error("身份证不合法"));
      } else {
        callback();
      }
    };
    let valPhone = (rule, value, callback) => {
      if (value) {
        if (!vm.regExpPhone(value)) {
          callback(new Error("电话号码不合法"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    return {
      formAuth:"",
      current: 1,
      pageSize: 10,
      total: 0,
      wuqId: "",
      wuqTitle: "",
      tableLoading: false,
      handleTitle: "",
      rechargeTitle: "",
      handleVisible: false,
      delVisible: false,
      rechargeVisible: false,
      showProgress: false,
      dialogVisibleAuth:false,
      percentageNum: 0,
      arrAuth:{},
      companyForm: {
        wuqTitle: "",
        wuqArea: "",
        wuqName: "",
        wuqCard: "",
        wuqPhone: "",
        wuqLicense: "",
        wuqLatitude: "",
        wuqLongitude: "",
        wuqArea: "",
        allowedRange: "",
      },
      rechargeForm: {
        balance: 0,
      },
      companyFormRule: {
        wuqTitle: [
          { required: true, message: "请输入企业名称", trigger: "blur" },
        ],
        wuqName: [{ required: true, message: "请输入法人", trigger: "blur" }],
        wuqCard: [{ required: false, validator: valCard, trigger: "blur" }],
        wuqPhone: [{ required: false, validator: valPhone, trigger: "blur" }],
        wuqArea: [
          { required: true, message: "请输入企业地址", trigger: "blur" },
        ],
        allowedRange: [
          { required: true, message: "请输入打卡范围", trigger: "blur" },
        ],
      },
      map: null,
      getAddress: null,
      getAddCode: null,
      geocoder: [],
      markersArray: [],
    };
  },

  computed: {
    ...mapState({
      companyList: (state) => state.companyManage.companyList,
    }),
  },
  mounted() {
    this.getData();
  },
  methods: {
    ...mapActions("companyManage", [
      "getCompanyList",
      "addCompany",
      "editCompany",
      "removeCompany",
      "rechargeCompany",
    ]),
    indexMethod(index) {
      return (this.current - 1) * this.pageSize + 1 + index;
    },
    getData() {
      this.tableLoading = true;
      this.getCompanyList(this);
    },
    resetForm() {
      const vm = this;
      vm.companyForm = {
        wuqTitle: "",
        wuqArea: "",
        wuqName: "",
        wuqCard: "",
        wuqPhone: "",
        wuqLicense: "",
        wuqLatitude: "",
        wuqLongitude: "",
        wuqArea: "",
        allowedRange: "",
      };
      vm.$nextTick(() => {
        vm.$refs.companyForm.clearValidate();
      });
    },
    resetRechargeForm() {
      const vm = this;
      vm.rechargeForm = {
        balance: 0,
      };
      vm.$nextTick(() => {
        vm.$refs.rechargeForm.clearValidate();
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getData();
    },
    handleSearch() {
      this.current = 1;
      this.getData();
    },
    handleAdd() {
      const vm = this;
      vm.resetForm();
      vm.handleVisible = true;
      vm.handleTitle = "新增企业";
      vm.init();
    },
    async handleEdit(row) {
      const vm = this;
      vm.resetForm();
      vm.handleVisible = true;
      vm.handleTitle = "编辑企业";
      vm.companyForm = {
        wuqId: row.wuqId,
        wuqTitle: row.wuqTitle,
        wuqArea: row.wuqArea,
        wuqName: row.wuqName,
        wuqCard: row.wuqCard,
        wuqPhone: row.wuqPhone,
        wuqLicense: row.wuqLicense,
        wuqLatitude: row.wuqLatitude,
        wuqLongitude: row.wuqLongitude,
        wuqArea: row.wuqArea,
        allowedRange: row.allowedRange,
      };
      vm.init();
    },
    handleCheck(row) {
      let { wuqId } = row;
      this.$prompt("请输入审核意见", "提示", {
        confirmButtonText: "通过",
        cancelButtonText: "驳回",
      })
        .then(({ value }) => {
          check_api({
            wuqId,
            wuqOpinion: value,
            wuqStatus: 2,
          });
        })
        .catch(({ value }) => {
          console.log(value);

          check_api({
            wuqId,
            wuqOpinion: value,
            wuqStatus: 1,
          });
        });
    },
    handleDelete(row) {
      this.wuqId = row.wuqId;
      this.delVisible = true;
    },
    handleRecharge(row) {
      const vm = this;
      this.rechargeVisible = true;
      vm.rechargeForm = {
        wuqId: row.wuqId,
        balance: 0,
      };
    },
    deleteRow() {
      this.removeCompany(this);
    },
    async handleSave() {
      const vm = this;
      vm.getAddressDetails(vm.companyForm.wuqArea).then((res) => {
        vm.companyForm.wuqLatitude = res.lat;
        vm.companyForm.wuqLongitude = res.lng;
      });
      if (
        vm.companyForm.wuqLatitude == "" ||
        vm.companyForm.wuqLatitude === undefined ||
        vm.companyForm.wuqLongitude == "" ||
        vm.companyForm.wuqLongitude === undefined
      ) {
        vm.$message.error(
          "输入地址不正确或获取经纬度有误，请重新输入或搜素地址"
        );
        return false;
      }
      vm.$refs["companyForm"].validate((valid) => {
        if (valid) {
          if (vm.handleTitle === "新增企业") {
            vm.addCompany(vm);
          } else {
            vm.editCompany(vm);
          }
        } else {
          return false;
        }
      });
    },
    optRecharge() {
      this.rechargeCompany(this);
    },
    beforeAvatarUpload(file) {
      const vm = this;
      const fileItem = file.name.split(".");
      let fileType = fileItem[fileItem.length - 1].toLowerCase();
      const isImg = vm.$global.imgType.includes(fileType);
      if (!isImg) {
        this.$message.warning(`请上传正确的图片格式`);
        return false;
      }
      let bucketName = "img";
      vm.imgLoading = true;
      let fd = new FormData();
      fd.append("file", file);
      vm.showProgress = true;
      vm.percentageNum = 0;
      let url = Api.fileUpload.replace("{bucketName}", bucketName);
      vm.$axios({
        method: "post",
        url: url,
        data: fd,
        headers: { "Content-Type": "multipart/form-data" },
        timeout: 1000 * 60 * 60,
        onUploadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            let perc = Math.round(
              (progressEvent.loaded / progressEvent.total) * 100
            );
            vm.percentageNum = perc > 95 ? 95 : perc;
          }
        },
      })
        .then((res) => {
          if (res.code === 20002) {
            vm.percentageNum = 100;
            vm.showProgress = false;
            vm.companyForm.wuqLicense = res.data.filePath;
          } else {
            vm.percentageNum = 100;
            vm.showProgress = false;
            vm.uploadErr = res.msg;
          }
        })
        .catch((err) => {
          vm.percentageNum = 0;
          vm.showProgress = false;
          vm.uploadErr = err.message;
        });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    init() {
      var vm = this;
      maps.init("W3YBZ-NW734-APUUL-XQTC4-76L2T-NCF70", () => {
        var myLatlng = new qq.maps.LatLng(34.23053, 108.93425);
        var myOptions = {
          zoom: 16,
          center: myLatlng,
          mapTypeId: qq.maps.MapTypeId.ROADMAP,
        };
        vm.map = new qq.maps.Map(
          document.getElementById("container"),
          myOptions
        );
        //获取点击后的地址
        qq.maps.event.addListener(vm.map, "click", function (event) {
          // 获取点击后的地图坐标
          vm.companyForm.wuqLongitude = event.latLng.getLng();
          vm.companyForm.wuqLatitude = event.latLng.getLat();
          vm.getAddressCode();
        });

        //调用地址显示地图位置并设置地址
        vm.getAddress = new qq.maps.Geocoder({
          complete: function (result) {
            vm.map.setCenter(result.detail.location);
            vm.companyForm.wuqLongitude = result.detail.location.lng;
            vm.companyForm.wuqLatitude = result.detail.location.lat;
            var marker = new qq.maps.Marker({
              map: vm.map,
              position: result.detail.location,
            });
            vm.markersArray.push(marker);
            if (vm.markersArray.length > 1) {
              for (let i = 0; i < vm.markersArray.length - 1; i++) {
                vm.markersArray[i].setMap(null); // 清除标记
              }
            }
          },
        });
        //通过坐标来显示地图地址
        vm.getAddCode = new qq.maps.Geocoder({
          complete: function (result) {
            vm.companyForm.wuqArea = result.detail.address;
          },
        });
      });
    },
    getAddressDetails(address) {
      return new Promise((resolve, reject) => {
        maps.init("W3YBZ-NW734-APUUL-XQTC4-76L2T-NCF70", () => {
          let geocoder = new qq.maps.Geocoder();
          geocoder.getLocation(address);
          geocoder.setComplete((res) => {
            resolve({
              lng: res.detail.location.lng,
              lat: res.detail.location.lat,
            });
          });
          geocoder.setError(() => {
            resolve({ lng: "", lat: "" });
          });
        });
      });
    },
    //通过地址获得位置
    getAddressKeyword() {
      //通过getLocation();方法获取位置信息值
      this.getAddress.getLocation(this.companyForm.wuqArea);
    },
    // 通过坐标获得地址
    getAddressCode() {
      var lat = parseFloat(this.companyForm.wuqLatitude);
      var lng = parseFloat(this.companyForm.wuqLongitude);
      var latLng = new qq.maps.LatLng(lat, lng);
      //调用获取位置方法
      this.getAddCode.getAddress(latLng);
    },
    exportExcle() {
      const tHeader = ["企业名称", "法人", "手机号", "地址", "余额"];
      const filterVal = [
        "wuqTitle",
        "wuqName",
        "wuqPhone",
        "wuqArea",
        "balance",
      ];
      const list = this.companyList;
      const data = this.formatJson(filterVal, list);
      data.unshift(tHeader);
      console.log(data);
      xlsx.exportExcel(data, "企业列表");
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    
    //审核
    audit(row){
      this.dialogVisibleAuth = true
      this.arrAuth = row
    },
    saveAuth(){
      this.$axios({
        method: 'post',
        url: Api.handler,
        data: {
          wuqId : this.arrAuth.wuqId,
          wuqOpinion: this.formAuth,
          wuqStatus: this.arrAuth.wuqStatus
        }
      }).then(res => {
        if(res.code == 20005){
          this.$message.success(res.msg)
          this.dialogVisibleAuth = false
        }
      }).catch(() => {
        this.$message.error(res.msg)
      })
    },
    rejected(){
      this.$axios({
        method: 'post',
        url: Api.handler,
        data: {
          wuqId : this.arrAuth.wuqId,
          wuqOpinion: this.formAuth,
          wuqStatus: this.arrAuth.wuqStatus
        }
      }).then(res => {
        if(res.code == 20005){
          this.$message.success("驳回提交")
          this.dialogVisibleAuth = false
        }
      }).catch(() => {
        this.$message.error(res.msg)
      })
    }
  }
};
</script>


